import React, { useState, useEffect } from 'react';
import address from '../address';
import { getExamineList } from '../sysRedux/getAppList';
import { connect } from 'react-redux';
import { Table, Space, Button, Modal, Form, Input, Checkbox, Divider } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { Column } = Table;
const { confirm } = Modal;
const CheckboxGroup = Checkbox.Group;
let token = '' || localStorage.getItem('token');

const FailedReason = ({ visible, onCreate, onCancel }) => {
  const [form] = Form.useForm();
  return (
    <Modal
      visible={visible}
      title="驳回功能"
      okText="驳回"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item
          name="reason"
          label="驳回理由"
          rules={[
            {
              required: true,
              message: '请输入驳回原因!',
            },
          ]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const AdoptEvaluation = ({ visible, onCreate, onCancel }) => {
  const plainOptions = ['不错', '好用', '推荐'];
  const defaultCheckedList = [];

  const [form] = Form.useForm();
  const [checkedList, setCheckedList] = useState(defaultCheckedList);
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);

  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };

  return (
    <Modal
      visible={visible}
      title="功能评价"
      okText="评价"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item name="checkbox" label="选择评价(可多选)">
          <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const Examine = (props) => {
  const [failed, setFailed] = useState(false);
  const [adopt, setAdopt] = useState(false);
  const [id, setId] = useState(0);
  const [text, setText] = useState({});
  useEffect(() => {
    props.dispatch(getExamineList());
  }, []);
  let tableData = props.examineList;
  const onFailedCreate = (values) => {
    text.reason = values.reason;
    props.dispatch({
      type: 'ADD_FAILEDLIST',
      value: text
    });
    tableData.splice(tableData.indexOf(text), 1);
    props.dispatch({
      type: 'DELETEEXAMINELLIST',
      value: tableData
    });
    fetch(address + '/userstep/setReviewedFalse', {
      method: 'POST',
      mode: 'cors',
      headers: {
        'authorization': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: id, reason: values.reason })
    })
      .then(res => res)
      .then(d => {
      })
      .catch(err => {
        console.log(err)
      })
    setFailed(false);
  };

  const onAdoptCreate = (values) => {
    let evaluation = '';
    for (var elem of values.checkbox.values()) {
      evaluation += elem + ' ';
    }
    evaluation = evaluation.replace(/(^\s*)|(\s*$)/g, "");
    text.reason = evaluation;
    props.dispatch({
      type: 'ADD_ADOPTLIST',
      value: text
    });
    tableData.splice(tableData.indexOf(text), 1);
    props.dispatch({
      type: 'DELETEEXAMINELLIST',
      value: tableData
    });
    fetch(address + '/userstep/setReviewedTrue', {
      method: 'POST',
      mode: 'cors',
      headers: {
        'authorization': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: id, reason: text.reason })
    })
      .then(res => res)
      .then(d => {
      })
      .catch(err => {
        console.log(err)
      })
    setAdopt(false);
  };

  const columns = [
    {
      title: 'APP图标',
      key: 'icon',
      render: text => (
        <img src={text.icon} style={{ width: '25px' }} />
      )
    },
    {
      title: 'APP名称',
      dataIndex: 'appname',
      key: 'appname',
    },
    {
      title: '功能名称',
      dataIndex: 'funcname',
      key: 'funcname',
    },
    {
      title: '作者',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '详情',
      key: 'detail',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => viewDetails(record.id)}>详情</a>
        </Space>
      ),
    },
    {
      title: '审核',
      key: 'state',
      render: (text, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => {
            confirm({
              title: '确认通过此功能？',
              icon: <ExclamationCircleOutlined />,
              content: '同意后无法进行修改',
              okText: '同意',
              cancelText: '取消',
              onOk() {
                setId(record.id);
                setText(text);
                setAdopt(true);
              },
              onCancel() {
                console.log('取消审核');
              },
            });
          }}>通过</Button>
          <Button type="primary" danger onClick={() => {
            confirm({
              title: '确认驳回此功能？',
              icon: <ExclamationCircleOutlined />,
              content: '驳回后无法进行修改',
              okText: '驳回',
              cancelText: '取消',
              onOk() {
                setId(record.id);
                setText(text);
                setFailed(true);
                // FailedList(record.id, text)
              },
              onCancel() {
                console.log('取消审核');
              },
            });
          }}>驳回</Button>
        </Space>
      ),
    }
  ];

  const viewDetails = (id) => {
    props.history.push({ pathname: '/home/viewdetails', state: id });
  }
  return (
    <>
      <FailedReason
        visible={failed}
        onCreate={onFailedCreate}
        onCancel={() => {
          setFailed(false);
        }}
      />
      <AdoptEvaluation
        visible={adopt}
        onCreate={onAdoptCreate}
        onCancel={() => {
          setAdopt(false);
        }}
      />
      <Table columns={columns} dataSource={tableData} pagination={false} />
    </>
  )
}
const mapStateToProps = (state) => ({
  examineList: state.examinelist
})

export default connect(mapStateToProps)(Examine);
